package com.sanyue.springboot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Guan
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //输出uri -> 统一资源描述符
        String requestURI = request.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        String requestURL = request.getRequestURL().toString();
        log.info("preHandle拦截成功，uri={}",requestURI);
        log.info("preHandle拦截成功，url={}",requestURL);

        Object admin = request.getSession().getAttribute("admin");
        if(admin != null){ //放行

            return true;
        }
        //拦截，重新返回到登入的页面
        request.setAttribute("msg","没有登入，请重新登入");
        request.getRequestDispatcher("/").forward(request,response);

        return false;
    }

    /**
     * 目标方法执行后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle方法被执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion方法被执行");
    }
}
